<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/sockjs-client/1.3.0/sockjs.min.js"></script>
</head>
<body>
<div id="connect">
    <button onclick="connect()">连接</button>
    <button onclick="disconnect()">关闭</button>
</div>
<div id="input">
    <input id="msg" type="text"/>
    <button onclick="send()">发送</button>
</div>
<div id="response"></div>
<div id="status"></div>

</body>

<script>
    var stompClient = null;
    var from = null;
    var to = null;
    getUser();
    function getUser(){
        $.get('/user',function (data) {
            from = data;
            if (data == 'wyf'){
                to = 'admin';
            } else {
                to = 'wyf'
            }
            alert('当前用户为:' + from + ',' +"聊天对象为：" + to);
        })
    }

    function connect() {
        var socket = new SockJS('/endpoint');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            alert("连接成功");
            stompClient.subscribe('/user/topic/response', function(messageOutput) {
                $("#response").append(messageOutput.body + '<br>');
            });

            stompClient.subscribe('/topic/status', function(messageOutput) {
               $("#status").html(messageOutput.body);
            });


        });
    }

    function send() {
        msg = $("#msg").val()
        stompClient.send("/app/chat/" + to,{},msg);
    }
    function disconnect() {
        stompClient.disconnect();
        alert("关闭成功");
    }
</script>
</html>